package com.example.testapp.activity.activity.study;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewStub;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.testapp.R;
import com.example.testapp.activity.activity.SuperActivity;
import com.example.testapp.activity.fragment.ReadFragment;
import com.example.testapp.activity.model.User;
import com.example.testapp.activity.ui.component.PullToZoomScrollViewEx;
import com.example.testapp.activity.util.DateUtils;
import com.example.testapp.activity.util.SharePreferenceUtil;
import com.example.testapp.activity.view.dialog.DateDialog;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.IOException;

/**
 * 用户信息界面
 * Created by l on 2016/9/1.
 */
public class MyInfoActivity extends SuperActivity implements View.OnClickListener {

    private static final String TAG = "MyInfoActivity";

    private ImageView  mLogo;
    private TextView   mNameTV;
    private TextView   mSexTV;
    private TextView   mBirthdayTV;

    private  ViewStub viewStubModifyName; 		//修改姓名
    private  ViewStub viewStubModifySex; 		//修改性别
    private  ViewStub viewStubExit; 			//退出账户
    private ViewStub viewStubModifyPic;		//修改头像

    private PullToZoomScrollViewEx  scrollView;

    protected User user = new User();
    protected DateDialog dateDialog = new DateDialog();

    private static final String IMAGE_UNSPECIFIED = "image/*";
    private static final int PHOTO_GRAPH = 1; 				// 拍照
    private static final int PHOTO_ZOOM = 2; 				// 缩放
    private static final int PHOTO_RESOULT = 3; 			// 结果

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info);
        getWindow().setBackgroundDrawable(null);
        initView();
    }

    private void initView() {
        RelativeLayout headView = (RelativeLayout) this.findViewById(R.id.head);
        RelativeLayout back = (RelativeLayout) headView.findViewById(R.id.back_left);
        TextView  title = (TextView)headView.findViewById(R.id.head_title);

        scrollView = (PullToZoomScrollViewEx)findViewById(R.id.scroll_view);
        View  zoomView = LayoutInflater.from(this).inflate(R.layout.include_info_head, null, false);
        View  contentView = LayoutInflater.from(this).inflate(R.layout.include_info_content, null, false);
        scrollView.setZoomView(zoomView);
        scrollView.setScrollContentView(contentView);

        mLogo = (ImageView)zoomView.findViewById(R.id.logo);
        mLogo.setOnClickListener(this);
        ImageView  mCarmera = (ImageView)zoomView.findViewById(R.id.camera_photo);
        mCarmera.setOnClickListener(this);

        mNameTV = (TextView)contentView.findViewById(R.id.name);
        RelativeLayout nameRl = (RelativeLayout)contentView.findViewById(R.id.name_rl);
        nameRl.setOnClickListener(this);
        mSexTV = (TextView)contentView.findViewById(R.id.sex);
        RelativeLayout sexRL = (RelativeLayout) contentView.findViewById(R.id.sex_rl);
        sexRL.setOnClickListener(this);
        mBirthdayTV = (TextView)contentView.findViewById(R.id.brithday);
        RelativeLayout birthdayRL = (RelativeLayout)contentView.findViewById(R.id.brithday_rl);
        birthdayRL.setOnClickListener(this);
        TextView exit = (TextView)contentView.findViewById(R.id.exit);
        exit.setOnClickListener(this);

        back.setOnClickListener(this);
        title.setOnClickListener(this);
        title.setText("个人资料");

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int  mScreenHeight = metrics.heightPixels;
        int  mScreenWidth = metrics.widthPixels;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(mScreenWidth, (int)(9.0F * (mScreenWidth / 16.0F)));
        scrollView.setHeaderLayoutParams(params);

        // 更新用户生日
        dateDialog.setDateBtnListener(new DateDialog.DateBtnListener(){

            @Override
            public void pressDateBtn(int id) {
                switch (id){
                    case R.id.ok_button:
                        String brithday = mBirthdayTV.getText().toString();
                        if (!TextUtils.isEmpty(brithday)){
                            long date = DateUtils.getString2Date(brithday);
                            Log.i(TAG, " " + date);
                            user.birthday = date;
                            SharePreferenceUtil.saveUserInfo(mContext, user);
                            Toast.makeText(mContext, "更新成功!", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    default:
                        break;
                }
            }
        });

        fullData();
    }

    private void fullData() {
          User userInfo = mUserController.getUserInfo();
          if (userInfo != null){
              user = userInfo;
              if (!TextUtils.isEmpty(userInfo.picUrl)){
                  Picasso.with(mContext).load(userInfo.picUrl).placeholder(R.mipmap.touxiang).error(R.mipmap.touxing).into(mLogo);
              }

              if (!TextUtils.isEmpty(userInfo.name)){
                  mNameTV.setText(userInfo.name);
              }else {
                  mNameTV.setText("");
              }

              if (userInfo.gender == 2){
                  mSexTV.setText("女");
              }else if(userInfo.gender == 1){
                  mSexTV.setText("男");
              }

              if (userInfo.birthday != 0){
                  mBirthdayTV.setText(DateUtils.formatDate(userInfo.birthday));
              }else{
                  mBirthdayTV.setText("");
              }
          }
    }

    @Override
    public void onClick(View v) {
         switch (v.getId()){
             case R.id.head_title:
                 finish();
                 break;
             case R.id.logo:
             case R.id.camera_photo:  //换图片
                 if (viewStubModifyPic == null){
                    viewStubModifyPic = (ViewStub) this.findViewById(R.id.modify_picture);
                    View  view = viewStubModifyPic.inflate();
                    TextView  cancel = (TextView) view.findViewById(R.id.select_cancel);
                    TextView  selectPicture = (TextView)view.findViewById(R.id.photo_album);
                    TextView  selectCamera = (TextView)view.findViewById(R.id.photo_camera);
                    RelativeLayout backarea = (RelativeLayout)view.findViewById(R.id.blankarea);
                     backarea.setOnClickListener(new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
                             viewStubModifyPic.setVisibility(View.GONE);
                         }
                     });
                     cancel.setOnClickListener(new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
                             viewStubModifyPic.setVisibility(View.GONE);
                         }
                     });
                     selectPicture.setOnClickListener(new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
                             Intent intent = new Intent(Intent.ACTION_PICK, null);
                             intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
                             startActivityForResult(intent, PHOTO_ZOOM);  // 读取相册缩放图片
                             viewStubModifyPic.setVisibility(View.GONE);
                         }
                     });
                     selectCamera.setOnClickListener(new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
                             Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                             intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg")));
                             startActivityForResult(intent, PHOTO_GRAPH);  // 拍照
                             viewStubModifyPic.setVisibility(View.GONE);
                         }
                     });
                 }
                 viewStubModifyPic.setVisibility(View.VISIBLE);
                 break;
             case R.id.name_rl:  //修改用户姓名
                 if (viewStubModifyName == null){
                     viewStubModifyName = (ViewStub)this.findViewById(R.id.modify_name);
                     View view = viewStubModifyName.inflate();
                     final TextView ok = (TextView)view.findViewById(R.id.ok_button);
                     TextView cancel = (TextView)view.findViewById(R.id.cancel_button);
                     RelativeLayout backarea = (RelativeLayout) view.findViewById(R.id.blankarea);
                     final EditText   nameEdit = (EditText)view.findViewById(R.id.name_edittext);
                     if (mUserController.getUserInfo() != null){
                         nameEdit.setText(mUserController.getUserInfo().name);
                     }
                     backarea.setOnClickListener(new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
                             viewStubModifyName.setVisibility(View.GONE);
                         }
                     });

                     ok.setOnClickListener(new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
                             String newName = nameEdit.getText().toString();
                             if (!TextUtils.isEmpty(newName)){
                                 user.name = newName;
                                 SharePreferenceUtil.saveUserInfo(mContext, user);
                                 Toast.makeText(mContext, "更新成功", Toast.LENGTH_SHORT).show();
                                 viewStubModifyName.setVisibility(View.GONE);
                             }else {
                                 showToast("用户名不能为空");
                             }
                         }
                     });
                     cancel.setOnClickListener(new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
                             viewStubModifyName.setVisibility(View.GONE);
                         }
                     });
                 }
                 viewStubModifyName.setVisibility(View.VISIBLE);
                 break;
             case R.id.sex_rl:  //修改用户性别
                 if (viewStubModifySex == null){
                    viewStubModifySex = (ViewStub)this.findViewById(R.id.modify_sex);
                    View view = viewStubModifySex.inflate();
                    TextView  ok = (TextView) view.findViewById(R.id.ok_button);
                    TextView  cancel = (TextView)view.findViewById(R.id.cancel_button);
                    final TextView  radioBtnOne = (TextView)view.findViewById(R.id.nan_radiobtn);
                    final TextView  radioBtnTwo = (TextView)view.findViewById(R.id.nv_radiobtn);
                    RelativeLayout backarea = (RelativeLayout)view.findViewById(R.id.blankarea);
                    LinearLayout  nan = (LinearLayout)view.findViewById(R.id.nan);
                    LinearLayout  nv = (LinearLayout)view.findViewById(R.id.nv);
                    nan.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            setRbCheck(radioBtnOne, radioBtnTwo);
                            user.gender = 1;
                        }
                    });
                     nv.setOnClickListener(new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
                             setRbCheck(radioBtnTwo, radioBtnOne);
                             user.gender = 2;
                         }
                     });
                     if (mUserController.getUserInfo() != null){
                         int gender = mUserController.getUserInfo().gender;
                         if (gender == 2){
                             radioBtnTwo.setBackgroundResource(R.mipmap.rediobox1);
                         }else if(gender == 1){
                             radioBtnOne.setBackgroundResource(R.mipmap.rediobox2);
                         }
                     }
                     backarea.setOnClickListener(new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
                             viewStubModifySex.setVisibility(View.GONE);
                         }
                     });
                     ok.setOnClickListener(new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
                             SharePreferenceUtil.saveUserInfo(mContext, user);
                             Toast.makeText(mContext, "更新成功", Toast.LENGTH_SHORT).show();
                             viewStubModifySex.setVisibility(View.GONE);
                         }
                     });
                     cancel.setOnClickListener(new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
                             viewStubModifySex.setVisibility(View.GONE);
                         }
                     });
                 }
                 viewStubModifySex.setVisibility(View.VISIBLE);
                 break;
             case R.id.brithday_rl:  //修改用户生日
                 dateDialog.showDatePicker(this, mBirthdayTV);
                 break;
             case R.id.exit:  //退出当前账户
                 if (viewStubExit == null){
                     viewStubExit = (ViewStub)this.findViewById(R.id.modify_exit);
                     View view = viewStubExit.inflate();
                     TextView ok = (TextView) view.findViewById(R.id.ok_button);
                     TextView cancel = (TextView) view.findViewById(R.id.cancel_button);
                     TextView phoneSelect = (TextView) view.findViewById(R.id.phone_select);
                     RelativeLayout backarea = (RelativeLayout)view.findViewById(R.id.blankarea);
                     backarea.setOnClickListener(new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
                             viewStubExit.setVisibility(View.GONE);
                         }
                     });
                     if (mUserController.getUserInfo() != null){
                         phoneSelect.setText(mUserController.getUserInfo().phone);
                     }
                     ok.setOnClickListener(new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
                             mUserController.loginOut();
                             viewStubExit.setVisibility(View.GONE);
                             finish();
                         }
                     });
                     cancel.setOnClickListener(new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
                             viewStubExit.setVisibility(View.GONE);
                         }
                     });
                 }
                 viewStubExit.setVisibility(View.VISIBLE);
                 break;
         }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PHOTO_GRAPH && resultCode == -1){  // 拍照
            // 设置文件保存路径
            File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
            String path = picture.getPath();
            if (path != null && !path.equals("")){
                startPhotoZoom(Uri.fromFile(picture));
            }
        }else if (requestCode == PHOTO_ZOOM && data != null){  // 读取相册缩放图片
             Uri uri = data.getData();
             String[] proj = {MediaStore.Images.Media.DATA};
             Cursor cursor = this.managedQuery(uri, proj, null, null, null);
             if (cursor != null){
                 int column = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                 cursor.moveToFirst();
                 String path = cursor.getString(column);
                 Log.i(TAG, "before:" + path);
                 startPhotoZoom(data.getData());
             }else{
                 Toast.makeText(mContext, "读取相册文件失败", Toast.LENGTH_SHORT).show();
             }
        }else if (requestCode == PHOTO_RESOULT && data != null){  // 处理结果
             if (mUserController.getUserInfo() != null){
                 //处理图片
                 handlePicture(getTempUri());
                 mLogo.setImageURI(getTempUri());
             }
        }
    }

    /**
     * 处理磁盘图片,如果大于512*512 则缩小图片
     */
    private void handlePicture(Uri uri) {
        Rect rect = mBitmapUtils.getBitmapBounds(uri);
        int  area = rect.right * rect.bottom;
        if (area > 512 * 512){
            Bitmap  bitmap = mBitmapUtils.getBitmap(uri, 512, 512);
            mBitmapUtils.saveBitmap(bitmap, Environment.getExternalStorageDirectory().getAbsolutePath(), TEMP_PHOTO_FILE, Bitmap.CompressFormat.JPEG);
        }
    }

    /**
     * 生成一个图片URI
     * @return
     */
    private Uri getTempUri() {
        return Uri.fromFile(getTempFile());
    }

    public static final String TEMP_PHOTO_FILE = "vclubs_head_img";
    private File getTempFile() {
        if (isSDCardMounted()){
            File file = new File(Environment.getExternalStorageDirectory(), TEMP_PHOTO_FILE + ".jpg");

            try {
                file.createNewFile();
            } catch (IOException e) {
                Toast.makeText(mContext, "创建文件失败", Toast.LENGTH_LONG).show();
            }
            return file;
        }else{
            return null;
        }
    }

    private boolean isSDCardMounted() {
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED))
            return true;
        return false;
    }

    /**
     * 收缩图片
     * @param uri
     */
    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("return-data", false);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent, PHOTO_RESOULT);
    }

    /**
     * 单选按钮切换
     * @param rbTrue
     * @param rbFlase
     */
    private void setRbCheck(TextView rbTrue, TextView rbFlase) {
          rbTrue.setBackgroundResource(R.mipmap.rediobox1);
          rbFlase.setBackgroundResource(R.mipmap.rediobox2);
    }

    @Override
    protected void obtainInfo() {

    }
}
